package com.zhiyun.hxzy.service;

import com.zhiyun.hxzy.dao.CollectionDao;

import com.zhiyun.hxzy.dao.HomeWorkDao;
import com.zhiyun.hxzy.dao.StudentDao;
import com.zhiyun.hxzy.domain.Collection;
import com.zhiyun.hxzy.domain.Homework;
import com.zhiyun.hxzy.domain.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CollectionService {
    @Autowired
    private CollectionDao collectionDao;
    @Autowired
    private HomeWorkDao homeWorkDao;
    @Autowired
    private StudentDao studentDao;

    //收藏或取消收藏
    public void findByStudentIdAndHomeworkId(Long studentId, Long homeworkId) {
        Collection collection = collectionDao.findByStudentIdAndHomeworkId(studentId, homeworkId);
        Homework homework = homeWorkDao.getOne(homeworkId);
        if (collection == null) {
            Collection collection1 = new Collection();
            collection1.setStudent(studentDao.getOne(studentId));
            collection1.setHomework(homeWorkDao.getOne(homeworkId));
            collection1.setCollectionTime(new Date());
            collectionDao.save(collection1);
            homework.setCollections(homework.getCollections()+1);
            homeWorkDao.save(homework);
        } else {
            collectionDao.delete(collection);
            homework.setCollections(homework.getCollections()<=0?0:homework.getCollections()-1);
            homeWorkDao.save(homework);
        }
    }

    //获取总共收藏数量
    public Integer findCollectionsByHomeworkId(Long homeworkId){
        Homework homework = homeWorkDao.getOne(homeworkId);
        return homework.getCollections();
    }

    //判断该作业是否被收藏
    public boolean findByStudentIdAndHomeworkId2(Long homeworkId,Long studentId){
        Collection collection = collectionDao.findByStudentIdAndHomeworkId(studentId, homeworkId);
        if (collection == null){
            return false;
        }else {
            return true;
        }
    }

    //查询学生所收藏的作业
    public Page<Collection> findByStudentId(Long studentId,int pageNum,int pageSize){
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "collectionTime");
        Page<Collection> page = collectionDao.findByStudentId(studentId, pageRequest);
        return page;
    }

}
